﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;
using System.Printing;
using WPFSample.PrintWithMarginsSample;

namespace Notepad_Clone
{
    partial class NotepadClone : Window
    {
        PrintQueue prnqueue;
        PrintTicket prntkt;
        Thickness marginPage = new Thickness(1);

        void AddPrintMenuItems(MenuItem itemFile)
        {
            MenuItem itemSetup = new MenuItem();
            itemSetup.Header = "Page Set_up";
            itemSetup.Click += this.PageSetupOnClick;
            itemFile.Items.Add(itemSetup);

            MenuItem itemPrint = new MenuItem();
            itemPrint.Header = "_Print...";
            itemPrint.Command = ApplicationCommands.Print;
            itemFile.Items.Add(itemPrint);
            this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Print, this.PrintOnExecuted));
        }

        private void PageSetupOnClick(object sender, RoutedEventArgs e)
        {
            PageMarginsDialog dlg = new PageMarginsDialog();
            dlg.Owner = this;
            dlg.PageMargins = this.marginPage;
            if (dlg.ShowDialog().GetValueOrDefault())
            {
                this.marginPage = dlg.PageMargins;
            }
        }

        void PrintOnExecuted(object sender, ExecutedRoutedEventArgs args)
        {
            PrintDialog dlg = new PrintDialog();
            if (this.prnqueue != null)
            {
                dlg.PrintQueue = this.prnqueue;
            }

            if (this.prntkt != null)
            {
                dlg.PrintTicket = this.prntkt;
            }

            if (dlg.ShowDialog().GetValueOrDefault())
            {
                this.prnqueue = dlg.PrintQueue;
                this.prntkt = dlg.PrintTicket;

                PlainTextDocumentPaginator paginator = new PlainTextDocumentPaginator()
                {
                    PrintTicket = prntkt,
                    Text = this.txtbox.Text,
                    Header = this.strLoadedFile,
                    Typeface = new Typeface(this.txtbox.FontFamily, this.txtbox.FontStyle, this.txtbox.FontWeight, this.txtbox.FontStretch),
                    FaceSize = this.txtbox.FontSize,
                    TextWrapping = this.txtbox.TextWrapping,
                    Margins = this.marginPage,
                    PageSize = new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight)
                };

                dlg.PrintDocument(paginator, this.Title);
            }
        }
    }
}
